package com.bsb.acc.utils;

import com.bsb.acc.errorcode.BusinessErrorCode;
import com.smy.framework.core.config.Property;
import com.smy.framework.core.exception.ServiceException;
import com.smy.framework.core.util.DateUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图片上传工具类
 *
 * @Author: ligc
 * on 2019/2/13
 * @Description
 */
public class FileUploadUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUploadUtils.class);
    private static String UPLOADIMAGEURL = Property.getProperty("upload_image_url");
    private static String IDIMAGEURL = Property.getProperty("third_image_url");

    public static String uploadImage(byte[] files) {
        String saveDir = null;
        try {
            String date = DateUtil.getCurIntDate() + "";
            String dir = UPLOADIMAGEURL + date;
            logger.info("dir地址====================》dir={}", dir);
            File imageFile = new File(dir);
            if (!imageFile.exists() && !imageFile.isDirectory()) {
                imageFile.mkdir();
            }
            UUID name = UUID.randomUUID();
            saveDir = dir + "/" + name + ".png";
            logger.info("saveDir地址====================》saveDir={}", saveDir);
            byte[] bytes = files;
            try (FileOutputStream os = new FileOutputStream(saveDir)) {
                logger.info("write====================》file={}", files);
                os.write(bytes, 0, bytes.length);
            }
        } catch (Exception e) {
            throw new ServiceException(BusinessErrorCode.ERROR_IMAGE_FILE_FAIL.getCode(), "图片上传失败");
        }

        return saveDir;
    }

}
